<template>
  <div class="flex">
    <el-card class="w-12/100 user" :gutter="12" shadow="always">
      <el-input v-model="filterText" placeholder="栏目名称或ID" />
      <el-row  justify="space-between" >
      <el-link type="primary" @click="handleSelectAllClick">{{
        $t('cms.content.channel.allChannel')
      }}</el-link>
      <el-link type="primary" style="margin-right: 2px;" @click="handleFoldAndExplain">{{
        $t('cms.content.channel.expand')
      }}</el-link>
      </el-row>
      <el-scrollbar height="650">
        <el-tree
          ref="treeRef"
          node-key="id"
          :default-expand-all="defaultExpandAll"
          :data="channelOptions"
          :props="defaultProps"
          :highlight-current="true"
          :filter-node-method="filterNode"
          :expand-on-click-node="false"
          @node-click="handleChannelNodeClick"
        />
      </el-scrollbar>
    </el-card>
    <el-card class="w-88/100 user" style="margin-left: 10px" :gutter="12" shadow="hover">
      <!-- 搜索工作栏 -->
      <ContentWrap>
        <el-form
          class="-mb-15px"
          :model="queryParams"
          ref="queryFormRef"
          :inline="true"
          label-width="68px"
          ><el-form-item label="标题" prop="title">
            <el-input
              v-model="queryParams.title"
              placeholder="请输入标题"
              clearable
              class="!w-240px"
            />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select
              v-model="queryParams.status"
              placeholder="请选择状态"
              clearable
              class="!w-120px"
            >
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.CMS_CONTENT_STATUS)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="置顶" prop="topLevel">
            <el-select
              v-model="queryParams.topLevel"
              placeholder="请选择置顶"
              clearable
              class="!w-120px"
            >
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.CMS_OPEN_CLOSE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="标记" prop="dictMark">
            <el-select
              v-model="queryParams.dictMark"
              placeholder="请选择标记"
              clearable
              class="!w-120px"
            >
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.CMS_CONTENT_MARKS)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="区块" prop="dictBlock">
            <el-select
              v-model="queryParams.dictBlock"
              placeholder="请选择区块"
              clearable
              class="!w-120px"
            >
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.CMS_CONTENT_BLOCKS)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="发布时间" prop="releaseTime">
            <el-date-picker
              v-model="queryParams.releaseTime"
              value-format="YYYY-MM-DD HH:mm:ss"
              type="daterange"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
              class="!w-240px"
            />
          </el-form-item>
          <el-form-item>
            <el-button @click="handleQuery"
              ><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button
            >
            <el-button @click="resetQuery"
              ><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button
            >
          </el-form-item>
        </el-form>
      </ContentWrap>
      <!--新增和批量操作-->
      <!-- 列表 -->
      <ContentWrap>
        <el-table
          v-loading="loading"
          :data="list"
          :table-layout="tableLayout"
          ref="tableRef"
          row-key="id"
          style="width: 100%"
        >
          <el-table-column label="ID" align="center" prop="id" />
          <el-table-column
            label="标题"
            align="center"
            prop="title"
            width="600px"
            show-overflow-tooltip
          >
            <template #default="{ row }">
              <div style="text-align: left">
                <el-link :href="row.url" target="_blank"> {{ row.title }}</el-link>
                <el-tooltip v-if="row.topLevel > 0" placement="top-start">
                  <template #content>
                    {{ row.topLevel }}
                  </template>
                  <el-icon><Top /></el-icon>
                </el-tooltip>
                <DictTag
                  :type="DICT_TYPE.CMS_CONTENT_MARKS"
                  :value="row.dictMark"
                  v-if="row.dictMark"
                />
                <DictTag
                  :type="DICT_TYPE.CMS_CONTENT_BLOCKS"
                  :value="row.dictBlock"
                  v-if="row.dictBlock"
                />
                <el-tooltip v-if="row.originContentId" placement="top-start">
                  <template #content>
                    <el-icon class="ml-1 align-middle"><DocumentCopy /></el-icon>
                    {{ t(`cms.content.type.${row.createMode}`) }}:
                    <span v-if="row.siteId !== row.originContent.siteId"
                      >[{{ row.originContent.siteName }}]</span
                    >
                    {{ row.originContent.nodeNames.map((it: any) => it).join('>') }}
                  </template>
                  <el-icon><DocumentCopy /></el-icon>
                </el-tooltip>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="栏目" align="center" prop="channelName" />
          <el-table-column label="访问量" align="center" prop="views" />
          <el-table-column label="状态" align="center" prop="status">
            <template #default="scope">
              <dict-tag :type="DICT_TYPE.CMS_CONTENT_STATUS" :value="scope.row.status" />
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <Pagination
          :total="total"
          v-model:page="queryParams.pageNo"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </ContentWrap>
    </el-card>
  </div>
</template>
<script setup lang="ts" name="Content">
// 全局相关的 import
import { ref } from 'vue'
import type { ElTree } from 'element-plus'
import { Top, DocumentCopy } from '@element-plus/icons-vue'
import { useI18n } from '@/hooks/web/useI18n'
import { dateFormatter } from '@/utils/formatTime'
import * as ContentApi from '@/api/cms/content'
import { getContentChannelTreeApi } from '@/api/cms/channel'
import { handleTree, defaultProps } from '@/utils/tree'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
const { t } = useI18n() // 国际化
// const message = useMessage() // 消息弹窗
const defaultExpandAll = ref(false) //是否默认展开
const tableLayout = ref('auto')

// 列表相关的变量
const queryParams = reactive({
  channelId: undefined,
  title: undefined,
  dictBlock: undefined,
  dictMark: undefined,
  topLevel: undefined,
  status: undefined,
  releaseTime: [],
  orderStrs: 'count.views_desc,release_time_desc,id_desc',
  pageNo: 1,
  pageSize: 20
})

const message = useMessage() // 消息
const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数据
const queryFormRef = ref() // 搜索的表单
const tableRef = ref() // 表格的 Ref
//const selectedIds = ref<number[]>([]) // 表格的选中 ID 数组

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await ContentApi.getContentTopViewPageApi(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  tableRef.value.clearSelection()
  handleQuery()
}
const channel = ref<any>()

// 左侧栏目树形结构
const channelOptions = ref<Tree[]>([])
const treeRef = ref<InstanceType<typeof ElTree>>()
const getTree = async () => {
  const res = await getContentChannelTreeApi()
  channelOptions.value.push(...handleTree(res))
}
const filterText = ref('')
watch(filterText, (val) => {
  treeRef.value!.filter(val)
})
const filterNode = (value: string, data: Tree) => {
  if (!value) return true
  const nameFilter = data.name.includes(value)
  const idFilter = Number(value) === data.id
  return nameFilter || idFilter
}

//折叠展开
const handleFoldAndExplain = () => {
  const nodesMap = treeRef.value!.store.nodesMap
  for (let key in nodesMap) {
    nodesMap[key].expanded = !defaultExpandAll.value
  }
  defaultExpandAll.value = !defaultExpandAll.value
}
//全部栏目点击
const handleSelectAllClick = async () => {
  //取消栏目选中
  queryParams.channelId = undefined
  treeRef.value!.setCurrentKey(undefined)
  channel.value = undefined
  await getList()
}
const handleChannelNodeClick = async (row: { [key: string]: any }) => {
  queryParams.channelId = row.id
  channel.value = row
  await getList()
}

//标记 设置区块
const contentMarks = ref()
const contentBlocks = ref()
const contentPushTypes = ref()
const contentStatus = ref()
const init = () => {
  contentMarks.value = getIntDictOptions(DICT_TYPE.CMS_CONTENT_MARKS)
  contentBlocks.value = getIntDictOptions(DICT_TYPE.CMS_CONTENT_BLOCKS)
  contentPushTypes.value = getIntDictOptions(DICT_TYPE.CMS_CHANNEL_RULE_COLL_TYPE)
  contentStatus.value = getIntDictOptions(DICT_TYPE.CMS_CONTENT_STATUS)
}

// ========== 初始化 ==========
onMounted(async () => {
  await getTree()
  //取字典区块 标记数据
  await init()
  await getList()
})
</script>
